<template>
  <div class="course-center">
    <el-alert
      v-if="!hasStudentInfo"
      title="请先完善个人信息"
      type="warning"
      description="您需要先在个人中心完善院系、专业、年级、班级信息才能使用课程选退功能。"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    >
      <template #default>
        <el-button type="primary" size="small" @click="goToUserProfile">
          去完善信息
        </el-button>
      </template>
    </el-alert>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="可选课程" name="available">
        <!-- 搜索和筛选 -->
        <div class="filter-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索课程名称"
            style="width: 200px; margin-right: 10px"
            clearable
            @input="handleSearch"
          />
          <el-select v-model="semesterFilter" placeholder="学期筛选" clearable @change="handleSearch">
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </div>

        <el-table :data="filteredAvailableCourses" style="width: 100%" v-loading="loading">
          <el-table-column prop="name" label="课程名称" />
          <el-table-column prop="description" label="课程简介" />
          <el-table-column prop="credits" label="学分" width="80" />
          <el-table-column prop="type" label="类型" width="100" />
          <el-table-column prop="semester" label="学期" width="120" />
          <el-table-column prop="schedule" label="上课时间" width="150" />
          <el-table-column prop="location" label="上课地点" width="150" />
          <el-table-column label="课程容量" width="150">
            <template #default="scope">
              <el-progress 
                :percentage="Math.round((scope.row.currentStudents / scope.row.capacity) * 100)" 
                :format="() => `${scope.row.currentStudents}/${scope.row.capacity}`"
                :status="scope.row.currentStudents >= scope.row.capacity ? 'exception' : ''"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleSelectCourse(scope.row.id)"
                :disabled="isAlreadySelected(scope.row.id) || scope.row.currentStudents >= scope.row.capacity || !hasStudentInfo"
              >
                {{ isAlreadySelected(scope.row.id) ? '已选' : (scope.row.currentStudents >= scope.row.capacity ? '已满' : '选课') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div v-if="availableCourses.length === 0 && !loading" class="empty-tip">
          暂无可选课程
        </div>
      </el-tab-pane>
      <el-tab-pane label="已选课程" name="selected">
        <div class="action-bar">
          <el-button type="primary" @click="showCourseSchedule" :disabled="selectedCourses.length === 0">
            一键生成课程表
          </el-button>
        </div>
        
        <el-table :data="selectedCourses" style="width: 100%" v-loading="loading">
          <el-table-column prop="name" label="课程名称" />
          <el-table-column prop="description" label="课程简介" />
          <el-table-column prop="credits" label="学分" width="80" />
          <el-table-column prop="type" label="类型" width="100" />
          <el-table-column prop="semester" label="学期" width="120" />
          <el-table-column prop="schedule" label="上课时间" width="150" />
          <el-table-column prop="location" label="上课地点" width="150" />
          <el-table-column label="操作" width="160">
            <template #default="scope">
              <el-popconfirm
                :title="scope.row.type === '必修课程' ? '必修课程退选需线下办理，确定要退选吗？' : '确定要退选这门课程吗？'"
                @confirm="handleWithdrawCourse(scope.row.id, scope.row.type)"
              >
                <template #reference>
                  <el-button 
                    type="danger" 
                    size="small" 
                    :disabled="!hasStudentInfo || scope.row.hasGrade"
                  >
                    <span v-if="scope.row.hasGrade">已录成绩不可退课</span>
                    <span v-else>退课</span>
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <!-- 学分统计 -->
        <div class="credit-summary" v-if="selectedCourses.length > 0">
          <p>已选 {{ selectedCourses.length }} 门课程，总学分：{{ totalCredits }}</p>
        </div>
        
        <div v-if="selectedCourses.length === 0 && !loading" class="empty-tip">
          您还没有选择任何课程
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 课程详情对话框 -->
    <el-dialog
      title="课程详情"
      v-model="courseDetailVisible"
      width="600px"
    >
      <div v-if="currentCourse" class="course-detail">
        <h3>{{ currentCourse.name }}</h3>
        <p class="description">{{ currentCourse.description }}</p>
        
        <div class="detail-item">
          <span class="label">学分：</span>
          <span>{{ currentCourse.credits }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">课程类型：</span>
          <span>{{ currentCourse.type || '选修课程' }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">学期：</span>
          <span>{{ currentCourse.semester }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">上课时间：</span>
          <span>{{ currentCourse.schedule }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">上课地点：</span>
          <span>{{ currentCourse.location }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">课程容量：</span>
          <span>{{ currentCourse.currentStudents }}/{{ currentCourse.capacity }}</span>
          <span v-if="currentCourse.type === '必修课程'" style="color:#909399;font-size:12px;">（必修课程容量自动同步）</span>
        </div>
        
        <div class="detail-item">
          <span class="label">先修课程：</span>
          <span>{{ currentCourse.prerequisite || '无' }}</span>
        </div>
      </div>
    </el-dialog>
    
    <!-- 课程表对话框 -->
    <el-dialog
      title="我的课程表"
      v-model="scheduleDialogVisible"
      width="900px"
    >
      <div class="course-schedule">
        <table>
          <thead>
            <tr>
              <th>时间段</th>
              <th>星期一</th>
              <th>星期二</th>
              <th>星期三</th>
              <th>星期四</th>
              <th>星期五</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(time, timeIndex) in timeSlots" :key="timeIndex">
              <td>{{ time }}</td>
              <td v-for="day in 5" :key="day">
                <div 
                  v-for="course in getCoursesForTimeSlot(timeIndex, day-1)" 
                  :key="course.id"
                  class="schedule-course"
                >
                  {{ course.name }}<br>
                  {{ course.location }}
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

export default {
  name: 'CourseCenter',
  props: {
    studentId: {
      type: [Number, String], // 支持数字或字符串类型的ID
      required: true
    }
  },
  setup(props) {
    const router = useRouter()
    const activeTab = ref('available')
    const availableCourses = ref([])
    const selectedCourses = ref([])
    const loading = ref(false)
    const searchQuery = ref('')
    const semesterFilter = ref('')
    const courseDetailVisible = ref(false)
    const currentCourse = ref(null)
    const hasStudentInfo = ref(false)
    const scheduleDialogVisible = ref(false)
    const scheduleData = ref([])
    
    // 时间段定义
    const timeSlots = [
      '8:00-9:40',
      '10:00-11:40',
      '14:00-15:40',
      '16:00-17:40',
      '19:00-20:40'
    ]

    // 计算总学分
    const totalCredits = computed(() => {
      return selectedCourses.value.reduce((sum, course) => sum + course.credits, 0);
    });

    // 过滤可选课程
    const filteredAvailableCourses = computed(() => {
      let result = [...availableCourses.value]
      
      if (searchQuery.value) {
        result = result.filter(course => 
          course.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          course.description.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }
      
      if (semesterFilter.value) {
        result = result.filter(course => course.semester === semesterFilter.value)
      }
      
      return result
    });
    
    // 检查课程是否已经选择
    const isAlreadySelected = (courseId) => {
      return selectedCourses.value.some(course => course.id === courseId);
    };
    
    // 检查学生是否已完善个人信息
    const checkStudentInfo = async () => {
      try {
        const response = await axios.get(`/api/users/${props.studentId}`)
        const user = response.data
        
        // 检查是否已设置院系、专业、年级、班级
        hasStudentInfo.value = !!(user.departmentId && user.majorId && user.grade && user.className)
        
        console.log('学生信息检查结果:', hasStudentInfo.value ? '已完善' : '未完善')
        
        // 如果学生已完善信息且是必修课程类型，自动选择必修课程
        if (hasStudentInfo.value && user.departmentId && user.majorId) {
          selectRequiredCourses(user.departmentId, user.majorId)
        }
      } catch (error) {
        console.error('获取学生信息失败:', error)
        hasStudentInfo.value = false
      }
    }
    
    // 自动选择必修课程
    const selectRequiredCourses = async (departmentId, majorId) => {
      try {
        await axios.post(`/api/courses/select-required?studentId=${props.studentId}&departmentId=${departmentId}&majorId=${majorId}`)
        console.log('自动选择必修课程完成')
      } catch (error) {
        console.error('自动选择必修课程失败:', error)
      }
    }
    
    // 跳转到个人信息页面
    const goToUserProfile = () => {
      router.push('/dashboard')
    }

    const fetchAvailableCourses = async () => {
      loading.value = true
      try {
        console.log('获取可选课程，studentId:', props.studentId);
        const response = await axios.get(`/api/courses?studentId=${props.studentId}`)
        availableCourses.value = response.data || []
        
        // 调试信息
        if (availableCourses.value.length > 0) {
          console.log('课程数据示例:', JSON.stringify(availableCourses.value[0]));
        } else {
          console.log('没有可选课程数据');
        }
      } catch (error) {
        console.error('获取可选课程失败:', error)
        ElMessage.error('获取可选课程失败')
      } finally {
        loading.value = false
      }
    }

    const fetchSelectedCourses = async () => {
      loading.value = true
      try {
        console.log('获取已选课程，studentId:', props.studentId);
        const response = await axios.get(`/api/users/me/courses?studentId=${props.studentId}`)
        selectedCourses.value = (response.data || []).map(course => ({
          ...course,
          hasGrade: !!(course.regularGrade || course.examGrade || course.finalGrade)
        }))
        console.log('已选课程数据:', selectedCourses.value);
      } catch (error) {
        console.error('获取已选课程失败:', error)
        ElMessage.error('获取已选课程失败')
      } finally {
        loading.value = false
      }
    }

    // 处理选课操作，确保课程ID正确传递
    const handleSelectCourse = async (courseId) => {
      if (!hasStudentInfo.value) {
        ElMessage.warning('请先完善个人信息')
        return
      }
      
      try {
        // 检查是否已经选了这门课
        if (isAlreadySelected(courseId)) {
          ElMessage.warning('您已经选择了这门课程')
          return
        }
        
        // 确保使用字符串形式的ID
        const courseIdStr = String(courseId);
        console.log('选课，studentId:', props.studentId, 'courseId:', courseIdStr, '课程ID类型:', typeof courseIdStr);
        
        const response = await axios.post(`/api/courses/${courseIdStr}/select?studentId=${props.studentId}`)
        if (response.data) {
          ElMessage.success('选课成功')
          // 重新获取课程数据
          await fetchSelectedCourses()
          await fetchAvailableCourses()
        } else {
          ElMessage.warning('选课失败，可能课程已满或已选过')
        }
      } catch (error) {
        console.error('选课失败:', error)
        ElMessage.error('选课失败')
      }
    }

    // 处理退课操作，确保课程ID正确传递
    const handleWithdrawCourse = async (courseId, courseType) => {
      if (!hasStudentInfo.value) {
        ElMessage.warning('请先完善个人信息')
        return
      }
      
      try {
        // 确保使用字符串形式的ID
        const courseIdStr = String(courseId);
        console.log('退课，studentId:', props.studentId, 'courseId:', courseIdStr);
        
        if (courseType === '必修课程') {
          ElMessage.warning('必修课程退选需线下办理')
          return
        }
        
        const response = await axios.delete(`/api/courses/${courseIdStr}/withdraw?studentId=${props.studentId}`)
        if (response.data) {
          ElMessage.success('退课成功')
          // 重新获取课程数据
          await fetchSelectedCourses()
          await fetchAvailableCourses()
        } else {
          ElMessage.warning('退课失败')
        }
      } catch (error) {
        console.error('退课失败:', error)
        ElMessage.error('退课失败')
      }
    }
    
    // 显示课程详情
    const showCourseDetail = (course) => {
      currentCourse.value = course
      courseDetailVisible.value = true
    }
    
    // 处理搜索
    const handleSearch = () => {
      console.log('搜索条件更新，关键词:', searchQuery.value, '学期:', semesterFilter.value)
    }
    
    // 生成课程表
    const showCourseSchedule = async () => {
      try {
        const response = await axios.get(`/api/users/me/course-schedule?studentId=${props.studentId}`)
        scheduleData.value = response.data || []
        scheduleDialogVisible.value = true
      } catch (error) {
        console.error('获取课程表失败:', error)
        ElMessage.error('获取课程表失败')
      }
    }
    
    // 获取指定时间段和星期的课程
    const getCoursesForTimeSlot = (timeIndex, dayIndex) => {
      const timeSlot = timeSlots[timeIndex]
      const dayText = ['一', '二', '三', '四', '五'][dayIndex]
      const pattern = `星期${dayText}${timeSlot}`
      
      return selectedCourses.value.filter(course => 
        course.schedule && course.schedule.includes(pattern)
      )
    }

    let timer = null
    onMounted(() => {
      console.log('CourseCenter组件挂载，studentId:', props.studentId);
      checkStudentInfo()
      fetchAvailableCourses()
      fetchSelectedCourses()
      // 定时轮询刷新
      timer = setInterval(() => {
        fetchAvailableCourses()
        fetchSelectedCourses()
      }, 5000)
    })
    onUnmounted(() => {
      if (timer) clearInterval(timer)
    })

    return {
      activeTab,
      availableCourses,
      selectedCourses,
      loading,
      searchQuery,
      semesterFilter,
      filteredAvailableCourses,
      totalCredits,
      courseDetailVisible,
      currentCourse,
      handleSelectCourse,
      handleWithdrawCourse,
      showCourseDetail,
      isAlreadySelected,
      handleSearch,
      hasStudentInfo,
      goToUserProfile,
      scheduleDialogVisible,
      showCourseSchedule,
      timeSlots,
      getCoursesForTimeSlot
    }
  }
}
</script>

<style scoped>
.course-center {
  padding: 20px;
}

.filter-bar {
  display: flex;
  margin-bottom: 20px;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

.credit-summary {
  margin-top: 20px;
  text-align: right;
  font-weight: bold;
}

.course-detail .detail-item {
  margin-bottom: 10px;
}

.course-detail .label {
  font-weight: bold;
  margin-right: 10px;
}

.description {
  color: #606266;
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.course-schedule table {
  width: 100%;
  border-collapse: collapse;
}

.course-schedule th, .course-schedule td {
  border: 1px solid #dcdfe6;
  padding: 10px;
  text-align: center;
  vertical-align: top;
  height: 80px;
}

.course-schedule th {
  background-color: #f5f7fa;
  height: auto;
}

.schedule-course {
  background-color: #ecf5ff;
  border-radius: 4px;
  padding: 5px;
  margin-bottom: 5px;
  font-size: 12px;
  color: #409eff;
}
</style>